package com.heima.common.exception;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@ControllerAdvice  //控制器增强类
@Slf4j
public class ExceptionCatch {

    /**
     * 处理不可控异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception e){
        e.printStackTrace();
        log.error("catch exception:{}",e.getMessage());

        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理可控异常  自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult exception(CustomException e){
        log.error("catch exception:{}",e);
        return ResponseResult.errorResult(e.getAppHttpCodeEnum());
    }

    /**
     * validation Exception
     *
     * @param ex
     * @param request
     * @param response
     * @return ResultBody
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public ResponseResult bodyValidExceptionHandler(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        String fieldMsg;
        if(ex instanceof MethodArgumentNotValidException){
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException)ex).getBindingResult().getFieldErrors();
            fieldMsg = fieldErrors.get(0).getDefaultMessage();
        }else {
            fieldMsg = ((BindException) ex).getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        }
        ResponseResult resultBody = ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(),fieldMsg);
//                .msg(fieldMsg).httpStatus(HttpStatus.BAD_REQUEST.value()).path(request.getRequestURI());
        response.setStatus(resultBody.getCode());
        log.warn("==> warn:{} exception: ", resultBody, ex);
        return resultBody;
    }
}
